#include "mainwindow.h"
#include "qmenu.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow), isGridOn(false),isSideSlide(false)
{
    ui->setupUi(this);

    // 主窗口的命名
    setWindowTitle("SvgPainter");

    ui->view->setScene(&scene);
    ui->view->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    // 设置光标形状
    ui->view->setCursor(QCursor());
    // 关闭视图的滚轮滑动
    ui->view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 指定场景的逻辑坐标范围
    scene.setSceneRect(0,0,1000,1000);

    // 实现对封闭图形的颜色填充和线条边框颜色的选择
    QMenu *BrushMenu = new QMenu;
    QAction *nobrush = BrushMenu->addAction("无填充");
    QAction *normalbrush = BrushMenu->addAction("纯色填充");
    NoBrushAction();
    ui->WitchBrush->setMenu(BrushMenu);
    ui->spinBox->setRange(1, 200);
    // 对线条和填充的标签进行颜色初始化，其初始值为黑色
    ui->framecolorlabel->setStyleSheet("background-color: black");
    ui->paddingcolorlabel->setStyleSheet("background-color: black");

    QSvgGenerator svggenerator;
    QPainter painter;
    // 实现绘图操作开始在SVG图形上进行
    painter.begin(&svggenerator);
    // 场景 scene 渲染到 painter 中
    scene.render(&painter);
    // 结束绘图操作
    painter.end();

    // 侧边框的初始化
    // 左侧停靠
    ui->sidewidget->move(-ui->sidewidget->width(),0);
    // 将按钮的高度设置为侧边框的一半
    ui->pushButton->move(-1,ui->sidewidget->height()/2);
    // 侧边栏动画效果：平滑的进出、持续时间、始几何位置和大小，并保持原有的宽度和高度
    sidewidgetAnimation = new QPropertyAnimation(ui->sidewidget,"geometry");
    sidewidgetAnimation->setEasingCurve(QEasingCurve::InOutQuint);
    sidewidgetAnimation->setDuration(300);
    ui->sidewidget->setGeometry(-ui->sidewidget->width(), 0, ui->sidewidget->width(), ui->sidewidget->height());
    // 侧边框按钮的动画效果
    pushButtonAnimation = new QPropertyAnimation(ui->pushButton,"geometry");
    pushButtonAnimation->setEasingCurve(QEasingCurve::InOutQuint);
    pushButtonAnimation->setDuration(200);
    ui->pushButton->setGeometry(0,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height());
    ui->pushButton->setIcon(QIcon(":image/left.svg"));
    // 设置 widget 的初始几何位置和大小，并保持原有的宽度和高度
    ui->widget->setGeometry(0,0,ui->widget->width(),ui->widget->height());

    // 利用槽函数实现信号的触发
    connect(ui->paddingcolorlabel, &ColorLabel::LabelIsClicked, this, &MainWindow::PadLabelClicked);
    connect(ui->framecolorlabel, &ColorLabel::LabelIsClicked, this, &MainWindow::LineLabelClicked);
    connect(nobrush, &QAction::triggered, this, &MainWindow::NoBrushAction);
    connect(normalbrush, &QAction::triggered, this, &MainWindow::NormalBrushAction);
}

MainWindow::~MainWindow()
{
    delete ui;
}

// 设置画笔的状态，分为禁用画笔和激活画笔
void MainWindow::BanBrush(){
    scene.clearSelection();
    // 无刷状态
    NoBrushAction();
    ui->WitchBrush->setVisible(false);
    ui->WitchBrush->setEnabled(false);
}
void MainWindow::ActivateBrush(){
    scene.clearSelection();
    ui->WitchBrush->setVisible(true);
    ui->WitchBrush->setEnabled(true);
    NoBrushAction();
}

//设置侧边栏的状态，分为禁用侧边栏和激活侧边栏，在激活状态时才可以实现对应的功能
void MainWindow::BanSideWindow() {
    scene.clearSelection();
    BanBrush();
    ui->spinBox->setVisible(false);
    ui->spinBox->setEnabled(false);
    ui->widthlabel->setVisible(false);
    ui->widthlabel->setEnabled(false);
    ui->prompt2->setVisible(false);
    ui->prompt2->setEnabled(false);
    ui->framecolorlabel->setVisible(false);
    ui->framecolorlabel->setEnabled(false);
    sidewidgetAnimation->setStartValue(QRect(0,0,ui->sidewidget->width(),ui->sidewidget->height()));
    sidewidgetAnimation->setEndValue(QRect(-this->rect().width(),0,ui->sidewidget->width(),ui->sidewidget->height()));
    sidewidgetAnimation->start();

    pushButtonAnimation->setStartValue(QRect(ui->sidewidget->width()-2,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
    pushButtonAnimation->setEndValue(QRect(-1,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
    pushButtonAnimation->start();

    ui->pushButton->setIcon(QIcon(":image/left.svg"));
    ui->pushButton->setVisible(false);
    ui->pushButton->setEnabled(false);
    int widgeX = 0;
    int widgeWidth = this->rect().width();
    ui->widget->setGeometry(widgeX, 0, widgeWidth, ui->widget->height());

    isSideSlide = !isSideSlide;
}
void MainWindow::ActivateSideWindow(){
    scene.clearSelection();
    ui->spinBox->setVisible(true);
    ui->spinBox->setEnabled(true);
    ui->widthlabel->setVisible(true);
    ui->widthlabel->setEnabled(true);
    ui->prompt2->setVisible(true);
    ui->prompt2->setEnabled(true);
    ui->framecolorlabel->setVisible(true);
    ui->framecolorlabel->setEnabled(true);
    ui->pushButton->setVisible(true);
    ui->pushButton->setEnabled(true);
}

void MainWindow::on_MouseSelectAction_triggered()
{
    ActivateSideWindow();
    ActivateBrush();
    // 鼠标绘制矩形框进行多选
    ui->view->setDragMode(QGraphicsView::RubberBandDrag);
    ui->view->isDragOn = false;
    ui->view->CurrentAction = NOACTION;
    ui->view->setCursor(Qt::CursorShape::ArrowCursor);
}

void MainWindow::on_HandAction_triggered()
{
    BanSideWindow();
    ui->WitchBrush->setVisible(false);
    ui->WitchBrush->setEnabled(false);
    ui->view->CurrentAction = NOACTION;
    if(ui->view->isDragOn) {
        ui->view->setDragMode(QGraphicsView::RubberBandDrag);
        ui->view->isDragOn = false;
        ui->view->setCursor(Qt::CursorShape::ArrowCursor);
    }
    else {
        ui->view->isDragOn = true;
        // 通过鼠标拖动来平移视图
        ui->view->setDragMode(QGraphicsView::ScrollHandDrag);
        ui->view->setCursor(Qt::CursorShape::OpenHandCursor);
    }
}

// 实现视图画布的清理
void MainWindow::on_ClearAction_triggered()
{
    BanSideWindow();
    ui->WitchBrush->setVisible(false);
    ui->WitchBrush->setEnabled(false);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    ui->view->setCursor(Qt::CursorShape::ArrowCursor);
    this->scene.clear();
}


void MainWindow::on_LineAction_triggered()
{
    ActivateSideWindow();
    BanBrush();
    ui->WitchBrush->setVisible(false);
    ui->WitchBrush->setEnabled(false);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    // 当前操作去调用直线去绘图
    ui->view->CurrentAction = LINE;
    ui->view->setCursor(Qt::CursorShape::CrossCursor);
}

void MainWindow::on_BeziterAction_triggered()
{
    ActivateSideWindow();
    BanBrush();
    ui->WitchBrush->setVisible(false);
    ui->WitchBrush->setEnabled(false);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    // 当前操作去调用Beziter曲线去绘图
    ui->view->CurrentAction = BEZIER;
    ui->view->setCursor(Qt::CursorShape::CrossCursor);
}

void MainWindow::on_RectangleAction_triggered()
{
    ActivateSideWindow();
    ActivateBrush();
    ui->WitchBrush->setVisible(true);
    ui->WitchBrush->setEnabled(true);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    // 当前操作去调用矩形去绘图
    ui->view->CurrentAction = RECTANGLE;
    ui->view->setCursor(Qt::CursorShape::CrossCursor);
}


void MainWindow::on_EllipseAction_triggered()
{
    ActivateSideWindow();
    ActivateBrush();
    ui->WitchBrush->setVisible(true);
    ui->WitchBrush->setEnabled(true);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    // 当前操作去调用椭圆去绘图
    ui->view->CurrentAction = ELLIPSE;
    ui->view->setCursor(Qt::CursorShape::CrossCursor);
}

void MainWindow::on_TriangleAction_triggered()
{
    ActivateSideWindow();
    ActivateBrush();
    ui->WitchBrush->setVisible(true);
    ui->WitchBrush->setEnabled(true);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    ui->view->setDragMode(QGraphicsView::NoDrag);
    // 当前操作去调用三角形去绘图
    ui->view->CurrentAction = TRIANGLE;
    ui->view->setCursor(Qt::CursorShape::CrossCursor);
}

void MainWindow::on_SaveAction_triggered()
{
    BanSideWindow();
    // 设置当前视图为没有操作
    ui->view->CurrentAction = NOACTION;
    ui->view->setCursor(Qt::CursorShape::ArrowCursor);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    QSvgGenerator svggenerator;
    // 弹出文件保存对话框，获取用户选择的保存路径，并将路径设置给 svggenerator
    QString folderPath = QFileDialog::getSaveFileName(this, "Save Image", "", "PNG Images (*.svg)"); 
    svggenerator.setFileName(folderPath);
    // 获取场景的矩形区域
    QRectF sceneRect = this->scene.sceneRect();
    // 将SVG大小设置为场景矩形区域的大小
    svggenerator.setSize(sceneRect.size().toSize());
    QPainter painter;
    painter.begin(&svggenerator);
    this->scene.render(&painter);
    painter.end();
    }

void MainWindow::on_GridAction_triggered()
{
    BanSideWindow();
    ui->view->CurrentAction = NOACTION;
    ui->view->setCursor(Qt::CursorShape::ArrowCursor);
    ui->view->setDragMode(QGraphicsView::NoDrag);
    ui->view->isDragOn = false;
    if(isGridOn)
    {
        // 如果没有设置网格，当前场景的背景颜色就为白色
        scene.setBackgroundBrush(QBrush(QColor(Qt::white)));
        isGridOn = false;
    }
    else
    {
        // 设置表格图
        // 创建两个 QPolygonF 对象 mypolygon1 和 mypolygon2，分别表示网格线的形状
        QPolygonF mypolygon1,mypolygon2;
        // (0, 5) 和 (10, 5)两个点定义了一条水平线段，用于绘制网格中的水平网格线
        mypolygon1<<QPointF(0,5)<<QPointF(10,5);
        // (5,0) 和 (10, 5)两个点定义了一条竖直线段，用于绘制网格中的垂直网格线
        mypolygon2<<QPointF(5,0)<<QPointF(5,10);
        //  创建了一个大小为 10x10 像素的像素图像
        QPixmap pix(10,10);
        // 对象的像素内容填充为透明
        pix.fill(Qt::transparent);
        // QPainter 对象在 pix 上进行绘制操作
        QPainter painter(&pix);
        // 创建了一个 QVector 容器对象，用于存储实数（qreal）类型的数据
        QVector <qreal> dashes;
        // dashes 中存储了四个值为 0 的实数
        dashes<<0<<0<<0<<0;
        //自定义的网格颜色
        QPen pen(QColor("#D2B48C"), 0.4);
        //  设置画笔的虚线模式
        pen.setDashPattern(dashes);
        painter.setPen(pen);
        // 平移坐标系的原点位置
        painter.translate(0,0);
        // 绘制水平直线
        painter.drawPolyline(mypolygon1);
        // 绘制竖直直线
        painter.drawPolyline(mypolygon2);
        scene.setBackgroundBrush(pix);
        isGridOn = true;
    }
}

void MainWindow::on_pushButton_clicked()
{
    //显示侧边栏
    if(!isSideSlide)
    {
        sidewidgetAnimation->setStartValue(QRect(-this->rect().width(),0,ui->sidewidget->width(),ui->sidewidget->height()));
        sidewidgetAnimation->setEndValue(QRect(0,0,ui->sidewidget->width(),ui->sidewidget->height()));
        sidewidgetAnimation->start();

        pushButtonAnimation->setStartValue(QRect(-1,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        pushButtonAnimation->setEndValue(QRect(ui->sidewidget->width()-2,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        pushButtonAnimation->start();
        // 设置pushButton的形状
        ui->pushButton->setIcon(QIcon(":image/right.svg"));

        // 调整widge的位置和大小
        int widgeX = ui->sidewidget->width();
        ui->widget->setGeometry(widgeX, 0, this->rect().width()-widgeX, ui->widget->height());

        isSideSlide = true;
    }
    else
    {
        sidewidgetAnimation->setStartValue(QRect(0,0,ui->sidewidget->width(),ui->sidewidget->height()));
        sidewidgetAnimation->setEndValue(QRect(-this->rect().width(),0,ui->sidewidget->width(),ui->sidewidget->height()));
        sidewidgetAnimation->start();

        pushButtonAnimation->setStartValue(QRect(ui->sidewidget->width()-2,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        pushButtonAnimation->setEndValue(QRect(-1,ui->sidewidget->height()/2,ui->pushButton->width(),ui->pushButton->height()));
        pushButtonAnimation->start();

        ui->pushButton->setIcon(QIcon(":image/left.svg"));

        // 恢复widge的位置和大小
        int widgeX = 0;
        ui->widget->setGeometry(widgeX, 0, this->rect().width(), ui->widget->height());

        isSideSlide = false;
    }
}

// 对边框颜色的选中
void MainWindow::LineLabelClicked(const QColor color_input) {
    ui->view->PenForLine.setColor(color_input);
    QList<QGraphicsItem*> selectedItems = scene.selectedItems();
    foreach (QGraphicsItem* item, selectedItems) {
        CShape* shape = qgraphicsitem_cast<CShape*>(item);
        if (shape) {
            shape->setPen(ui->view->PenForLine);
        }
    }
    ui->framecolorlabel->setStyleSheet(QString("background-color: %1").arg(color_input.name()));
}

// 对封闭图形进行颜色的填充
void MainWindow::PadLabelClicked(const QColor color_input) {
    ui->view->BrushForShape = color_input;
    QList<QGraphicsItem*> selectedItems = scene.selectedItems();
    foreach (QGraphicsItem* item, selectedItems) {
        CShape* shape = qgraphicsitem_cast<CShape*>(item);
        if (shape) shape->setBrush(ui->view->BrushForShape);
    }
    ui->paddingcolorlabel->setStyleSheet(QString("background-color: %1").arg(color_input.name()));
}

// 对边框粗细的更改
void MainWindow::on_spinBox_valueChanged(int arg1)
{
    ui->view->PenForLine.setWidth(arg1);
    QList<QGraphicsItem*> selectedItems = scene.selectedItems();
    foreach (QGraphicsItem* item, selectedItems) {
        CShape* shape = qgraphicsitem_cast<CShape*>(item);
        if (shape) {
            shape->setPen(ui->view->PenForLine);
        }
    }
}

void MainWindow::NoBrushAction(){
    ui->WitchBrush->setText("无填充");
    ui->view->BrushForShape = Qt::NoBrush;
    ui->prompt3->setVisible(false);
    ui->paddingcolorlabel->setVisible(false);
    ui->paddingcolorlabel->setEnabled(false);
    QList<QGraphicsItem*> selectedItems = scene.selectedItems();
    foreach (QGraphicsItem* item, selectedItems) {
        CShape* shape = qgraphicsitem_cast<CShape*>(item);
        if (shape) shape->setBrush(ui->view->BrushForShape);
    }
}
void MainWindow::NormalBrushAction(){
    ui->WitchBrush->setText("纯色填充");
    ui->view->BrushForShape.setStyle(Qt::SolidPattern);
    ui->view->BrushForShape.setColor(ui->paddingcolorlabel->palette().color(QPalette::Window));
    ui->prompt3->setVisible(true);
    ui->paddingcolorlabel->setVisible(true);
    ui->paddingcolorlabel->setEnabled(true);
    ui->prompt3->setText("填充颜色:");
    QList<QGraphicsItem*> selectedItems = scene.selectedItems();
    foreach (QGraphicsItem* item, selectedItems) {
        CShape* shape = qgraphicsitem_cast<CShape*>(item);
        if (shape) shape->setBrush(ui->view->BrushForShape);
    }
}

void MainWindow::resizeEvent(QResizeEvent *event) {
    Q_UNUSED(event);
    // 如果侧边栏移动，widget的偏移量就等于侧边栏的偏移量；如果不移动，widget的偏移量就为0
    int DeltaX = isSideSlide ? ui->sidewidget->width():0;
    ui->widget->setGeometry(DeltaX, 0, this->rect().width()-DeltaX, this->rect().height());
}

